var router = require('express').Router();
var util = require('util');
var async = require('async');

var Consts = require('../consts');
var resultJson = require('../result-json');
var Utils = require('../utils');
var logger = require('../models/logger');
var Message = require('../models/Message');
var User = require('../models/User');
var Group = require('../models/Group');
var GroupMessage = require('../models/GroupMessage');


//添加群聊信息
router.post('/add', function(req, res) {
	var message = req.body;
	if (!message.media || !message.content ||!message.groupid)
		return res.send(resultJson(3));

	message.from = message._user._id;
	message.create = new Date();
  
	new GroupMessage(message).save(function(err, msg) {
		if (err) {
			logger.error(err);
			return res.send(resultJson(2));
		}
		var item = JSON.parse(JSON.stringify(msg));
		

        Group.findOne({
            _id: message.groupid
        }, function(err,group) {
            if (err)
                return res.send(resultJson(2));
            getGroupFriendList(item.from,group.groupuserid,group.name)

            User.findOne({
                _id: item.from
            }, {
                _id: 1,
                name: 1,
                photo: 1
            }).exec(function(err, user) {
                if (err)
                    res.send(resultJson(0));
                if (!user)
                    user = {};

                item.userName = user.name;
                item.userPhoto = user.photo;
                res.send(resultJson(0, item));
            });

        });


	})
});
function getGroupFriendList(index,friendList,groupName){
    
    var count=0;
    for(var i=0;i<friendList.length;i++){
        if(index != friendList[i]){
            User.findOne({
                _id: friendList[i],
            },{
                _id:1,
                name:1,
                photo:1,
                phone:1,
                category:1
            },function(err,user){
                if(err){
                  return res.send(resultJson(2));
                }
               ++count;
                var tomes = user.category == 30 ? '('+groupName+'群)有一条新消息!':'('+groupName+'group)has a new message!';
                var obj ={};
                obj.platform = [2];
                obj.alias = user.phone;
                obj.alertmsg = tomes;
                obj.contentmsg = 'test';
                var pus = new Object();
                pus.user = groupName;
                pus.type = 3;
                obj.option = {"extra":pus};
                Utils.pushMessage(obj); 

              if(count==friendList.length){
                return;
              }
            });
        }   
    }

}
// 获取群聊列表信息
router.post('/list', function(req, res) {
    var groupid = req.body.groupid;
 if(!groupid)
        return res.send(resultJson(3));

    var results = new Array();
 GroupMessage.findOne({
      groupid:groupid,
    }).sort({
        create: -1
    }).exec(function(err, message) {
        if (!err) {
            if(message) {
                results.push(message);
                return res.send(resultJson(0, results));
            }
        } else
            res.send(resultJson(2));
    });
 
});



//TODO
//获取聊天列表
router.post('/detail', function(req, res) {
    var groupid = req.body.groupid;
    if (!groupid)
        return res.send(resultJson(3));

    var query = GroupMessage.find({
       groupid:groupid
    });
    query.sort({
        create: 1
    });
    query.exec(function(err, msgs) {
       // console.log("聊天对象："+msgs);

        if (err)
            return res.send(resultJson(2));
        var results = new Array();
        referToUser(0,msgs,res,results);
    });
})

function referToUser(index,msgs,res,results){
     if(index==msgs.length){
        return res.send(resultJson(0, results));
    }
    results.push(msgs[index]);
    var userId = msgs[index].from;
    User.findOne({
        _id: userId
    }, function(err, user) {
        if (!user) {
            res.send(resultJson(2));
            return;
        }
        results[index] = JSON.parse(JSON.stringify(results[index]));
        results[index].name = user.name;
        results[index].photo = user.photo;
        results[index].category = user.category;
        results[index].sex = user.sex;
        index++;
        referToUser(index, msgs,res,results);
    });

}
module.exports = router;